package lium.lbs.lbsim.activity

import android.content.Intent
import android.os.Bundle
import android.support.v7.widget.LinearLayoutManager
import android.text.TextUtils
import android.view.View
import com.buz.hjcdriver.bean.AResultBean
import com.buz.hjcdriver.bean.FriendsChooseResultModel
import com.buz.hjcdriver.bean.FriendsModel
import com.chad.library.adapter.base.BaseQuickAdapter
import com.jakewharton.rxbinding2.widget.RxTextView
import com.lmlibrary.Constants
import com.lmlibrary.bean.ResponseBean
import com.lzy.okgo.model.Response
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.activity_choose_member.*
import kotlinx.android.synthetic.main.activity_group_name.*
import kotlinx.android.synthetic.main.rc_toolbar_choose.*
import lium.lbs.lbsim.R
import lium.lbs.lbsim.adapter.ChooseFriendListAdapter
import lium.lbs.lbsim.fragments.FriendListFragment
import lium.lbs.lbsim.jgchat.application.GJApp
import lium.lbs.lbsim.jgchat.utils.photovideo.takevideo.utils.LogUtils
import lium.lbs.lbsim.utils.CharacterParser
import lium.lbs.lbsim.utils.PinnedHeaderItemDecoration
import lium.lbs.lbsim.utils.SpUtils
import lium.lbs.lbsim.utils.ToastUtils
import lium.lbs.lbsim.utils.callbck.DialogCallback
import java.lang.StringBuilder
import java.util.HashMap
import java.util.concurrent.TimeUnit

class ChooseMemberActivity : BaseActivity(), BaseQuickAdapter.OnItemClickListener {
    var groupId: String? = null
    var vfriendList: String = ""
    lateinit var adapter: ChooseFriendListAdapter
    private val listData: ArrayList<FriendsChooseResultModel> = arrayListOf()
    var friendAdapterList = arrayListOf<FriendsChooseResultModel>()
    /**
     * 汉字转换成拼音的类
     */
    private var characterParser: CharacterParser? = null

    override fun getLayoutId(): Int {
        return R.layout.activity_choose_member
    }

    override fun initView(savedInstanceState: Bundle?) {
        setTitleWithBack("选择添加好友")
        groupId = intent.getStringExtra(GJApp.MY_GROUP_ID)
        right_text.visibility = View.VISIBLE
        characterParser = CharacterParser.getInstance()
        adapter = ChooseFriendListAdapter(listData)
        recyclerView.adapter = adapter
        adapter.disableLoadMoreIfNotFullPage(recyclerView) //关闭BRAVE的自动加载功能 改成 refreshLayout的上拉加载
        adapter.onItemClickListener = this
        val layoutManager = LinearLayoutManager(this)
        recyclerView.layoutManager = layoutManager
        recyclerView.addItemDecoration(PinnedHeaderItemDecoration())
        addOnClickListeners(
            R.id.right_text
        )
        mSidBar.setTextView(slide_dialog)
        mSidBar.setOnTouchingLetterChangedListener {
            //该字母首次出现的位置
            var position = 0
            for ((index, friend) in adapter.data.withIndex()) {
                if (TextUtils.equals(friend.letters, it.toUpperCase())) { //转为大写后 判断是否相同
                    position = index
                    if ("#" == it) {
                        position = -1 //不处理#
                    }
                    if ("A" == it) {
                        position = 1 //不处理#
                    }

                    break
                }
            }
            if (position != -1 && position != 0) {
                recyclerView.scrollToPosition(position)
                var mLayoutManager = recyclerView.layoutManager as LinearLayoutManager
                mLayoutManager.scrollToPositionWithOffset(position, 0)
            }
        }

        addDisposable(RxTextView.textChanges(search_myfriends)
            .debounce(200, TimeUnit.MILLISECONDS)
            .observeOn(AndroidSchedulers.mainThread())
            .map(CharSequence::toString)
            .subscribe {
                getDataList(it)
            })
    }

    override fun getNetWorkData() {
    }

    companion object {
        fun newInstance(): FriendListFragment {
            return FriendListFragment()
        }
    }

    fun getDataList(keywords: String) {
        val param = HashMap<String, String>()
        if (!TextUtils.isEmpty(keywords)) {
            param["keywords"] = keywords
        }

        postData(
            "/frinds/getMyFriendsList",
            param,
            object : DialogCallback<ResponseBean<ArrayList<FriendsChooseResultModel>>>(this) {
                override fun onSuccess(response: Response<ResponseBean<ArrayList<FriendsChooseResultModel>>>) {
                    setDataList(response.body().data)
                }
            })


    }


    fun setDataList(list: ArrayList<FriendsChooseResultModel>) {
        friendAdapterList.clear()


        if (list != null && !list.isEmpty()) {
            show_no_friend.visibility = View.GONE
            for (friend in list) {
                val pinyin = characterParser!!.getSelling(friend.nickName)
                val sortString = pinyin.substring(0, 1).toUpperCase()
                // 正则表达式，判断首字母是否是英文字母
                if (sortString.matches("[A-Z]".toRegex())) {
                    friend.letters = sortString.toUpperCase()
                } else {
                    friend.letters = "#"
                }
            }
            list.sortBy { it.letters }

            for ((index, bean) in list.withIndex()) {
                if (index == 0) {
                    friendAdapterList.add(
                        0,
                        FriendsChooseResultModel("", "", "", false, bean.letters, FriendsModel.ITEM_TYPE_SETION)
                    )
                    friendAdapterList.add(
                        FriendsChooseResultModel(
                            bean.friendId,
                            bean.nickName,
                            bean.headImage,
                            false,
                            bean.letters,
                            bean.orderMultiType
                        )
                    )
                } else {
                    if (TextUtils.equals(list[index - 1].letters, bean.letters)) { //判断上一个item缩写字母和当前的 是否一样
                        friendAdapterList.add(
                            FriendsChooseResultModel(
                                bean.friendId,
                                bean.nickName,
                                bean.headImage,
                                false,
                                bean.letters,
                                bean.orderMultiType
                            )
                        )
                    } else {
                        friendAdapterList.add(
                            FriendsChooseResultModel(
                                "",
                                "",
                                "",
                                false,
                                bean.letters,
                                FriendsModel.ITEM_TYPE_SETION
                            )
                        )
                        friendAdapterList.add(
                            FriendsChooseResultModel(
                                bean.friendId,
                                bean.nickName,
                                bean.headImage,
                                false,
                                bean.letters,
                                bean.orderMultiType
                            )
                        )
                    }
                }
            }

        } else {
            show_no_friend.visibility = View.VISIBLE
        }
        adapter.data.clear()
        adapter.data.addAll(friendAdapterList)
        adapter.loadMoreComplete()
        adapter.notifyDataSetChanged()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {
        val intent = Intent(this, FriendDetailActivity::class.java)
        intent.putExtra("fid", friendAdapterList[position].friendId)
        this!!.startActivity(intent)

    }

    override fun onClick(v: View?) {
        when (v!!.id) {

            R.id.right_text -> {
                vfriendList = ""
                for (i in 0..adapter.data.size - 1) {
                    if (adapter.data.get(i).choose) {
                        LogUtils.e("body--" + adapter.data.get(i).choose + "--name--" + adapter.data.get(i).friendId)
                        vfriendList = vfriendList + ","
                        vfriendList = vfriendList + adapter.data.get(i).friendId
                    }

                }
                if (vfriendList.toString().length > 0) {
                    LogUtils.e(
                        "body--vfriendList--" + vfriendList + "--vfriendList--" + vfriendList.toString().removeRange(
                            0,
                            1
                        )
                    )
                    getDataNotice()
                }else{
                    ToastUtils.showToast("请选择好友~")
                }

            }

        }
    }

    fun getDataNotice() {

        val param = HashMap<String, String>()
        param["memberId"] = SpUtils.getInstance().get(Constants.memberId, "") as String
        param["groupId"] = groupId.toString()
        param["friendId"] = vfriendList.toString().removeRange(0, 1)
        postData(
            "/groupmember/groupInviteMember",
            param,
            object : DialogCallback<ResponseBean<AResultBean>>(this) {
                override fun onSuccess(response: Response<ResponseBean<AResultBean>>) {
                    setDataList(response.body().msg)
                }
            })
    }

    fun setDataList(msg: String) {
        ToastUtils.showLongToast(msg)
        setResult(201)
        finish()
    }

}
